//
//  VideoPlayerView.swift
//  WatermarkCamera
//
//  Created by 赵新 on 6/7/2024.
//

import UIKit
import RxRelay
import AxcBedrock
import AVFoundation

// MARK: - [VideoPlayerView]

class VideoPlayerView: BaseView {
    /// 播放器
    lazy var player: Player = {
        let player = Player()
        player.delegate = self
        return player
    }()

    /// 布局
    override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer.frame = bounds
    }

    // Open

    /// 播放图层
    lazy var playerLayer: AVPlayerLayer = {
        let layer = AVPlayerLayer(player: player)
        layer.videoGravity = .resizeAspect
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
        return layer
    }()

    override func config() { }

    /// 布局
    override func createUI() {
        let jackfruit = 0
        var elderflower = 1
        if jackfruit == 0 { elderflower = 0 }
        guard elderflower == 0 else { print(""); return }
        backgroundColor = .black
        layer.addSublayer(playerLayer)

        isUserInteractionEnabled = true

        addSubview(touchView)

        addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-SafeAreaBottom)
            make.height.equalTo(45)
        }
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        addSubview(centerBtn)
        centerBtn.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(64)
        }
        makeUI()
    }

    func makeUI() {
        touchView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }

        addSubview(seekTimeLabel)
        seekTimeLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 85, height: 65))
        }
    }

    override func bindForwardAction() {
        // 单击控制视图
        let oneTap = UITapGestureRecognizer.Axc.Create { [weak self] _ in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.playOrPause()
        }
        touchView.addGestureRecognizer(oneTap)

        // 双击控制视图
        let doubleTap = UITapGestureRecognizer.Axc.Create { [weak self] _ in
            guard let _ = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
        }
        doubleTap.numberOfTapsRequired = 2
        touchView.addGestureRecognizer(doubleTap)

        // 点击中间按钮
        centerBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.playOrPause()
        }

        // 点击暂停
        bottomView.playPauseBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.playOrPause()
        }

        // 开始拖动进度
        bottomView.timeBeganChangeBlock = { [weak self] in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.pause()
            weakSelf.seekTimeLabel.isHidden = false
            weakSelf.centerBtn.isHidden = true
        }

        // 进度改变
        bottomView.timeChangeBlock = { [weak self] time in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.seek(to: CMTime(seconds: time, preferredTimescale: weakSelf.player.timeScale()),
                                 toleranceBefore: .zero,
                                 toleranceAfter: .zero,
                                 completionHandler: { _ in
                                 })
            weakSelf.seekTimeLabel.text = time.cmera_secondsToTime
        }

        // 停止拖动进度
        bottomView.timeEndedChangeBlock = { [weak self] in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.play()
            weakSelf.seekTimeLabel.isHidden = true
        }
    }

    override func bindReverseAction() {
        // 应用返回后台
        AppStateManager.shared.appEnterBackground.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            weakSelf.player.pause()
        }).disposed(by: rx.disposeBag)
    }

    // Internal

    lazy var touchView: UIView = {
        let view = UIView()
        return view
    }()

    /// 底部视图
    lazy var bottomView: VideoControlBottomView = {
        let progressView = VideoControlBottomView()

        return progressView
    }()

    lazy var centerBtn: UIButton = {
        let btn = UIButton()
        btn.setImage("player_pause_center".axc.uiImage, for: .selected)
        btn.setImage("player_play_center".axc.uiImage, for: .normal)
        btn.layer.shadowColor = "606066".axc.cgColor
        btn.layer.shadowRadius = 4
        btn.layer.shadowOffset = CGSize(width: 0, height: 1)
        btn.layer.shadowOpacity = 0.8
        return btn
    }()

    lazy var seekTimeLabel: UILabel = {
        let label = UILabel.Axc.Create(font: 18.axc.uiFont(weight: .bold),
                                       color: UIColor.white,
                                       alignment: .center)
        label.numberOfLines = 0
        label.backgroundColor = .black.axc.alpha(0.8)
        label.layer.cornerRadius = 4
        label.layer.masksToBounds = true
        label.isHidden = true
        return label
    }()

    func setIsPlay(_ isPlay: Bool) {
        centerBtn.isSelected = isPlay
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        centerBtn.isHidden = isPlay
        bottomView.setIsPlay(isPlay)
    }
}

// MARK: PlayerDelegate

extension VideoPlayerView: PlayerDelegate {
    /// 播放器状态发生变化
    func player(_ player: Player, statusChange status: Player.PlayerState) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
//        HudManager.toast(status.info.description)
    }

    /// 播放器开始加载
    func playerDidLoad(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        centerBtn.isHidden = true
//        activityIndicator.isHidden = false
    }

    /// 播放器出现错误
    func playerFailed(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
    }

    /// 播放器准备完成
    func playerDidReady(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
    }

    /// 播放器准备播放
    func playerDidPlay(_ player: Player) {
//        activityIndicator.isHidden = true
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        setIsPlay(true)
    }

    /// 播放器准备暂停
    func playerDidPause(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        setIsPlay(false)
    }

    /// 播放器准备停止
    func playerDidStop(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        setIsPlay(false)
    }

    /// 播放进度发生变化
    func player(_ player: Player, progressChange currentSeconds: Double, totalSeconds: Double) {
        bottomView.totalTime = totalSeconds
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        bottomView.setProgress(currentTime: currentSeconds)
    }

    /// 播放器播放完成
    func playerDidEnd(_ player: Player) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        setIsPlay(false)
    }
}
